package racer.client.gui.mapgen;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;

import java.io.IOException;
import javax.imageio.ImageIO;

import java.util.HashMap;



public class ImageBank {
	
    private String images_path = "images/themes";

 
    private static HashMap<String,BufferedImage> images;
    
	public ImageBank(String images_subdir) {
		System.out.println("Listing images files and directories");
                images_path+="/"+images_subdir;
		images = new HashMap<String,BufferedImage>();
                
		loadImages(new File(images_path));
                
	}
	
	// recursively loads all images in root -and subdirectories
	private void loadImages(File file) {
		
		if (file.isDirectory()) {
			String[] children = file.list();
			for (int i=0; i<children.length; i++) {
				loadImages(new File(file,children[i]));
			}
		} else if(file.isFile() && !file.isHidden()) {
			int ext_pos = file.getName().lastIndexOf(".");
			if (ext_pos == -1) {
				return;
			}
			
			String filename = file.getName().substring(0, ext_pos);
			String extension = file.getName().substring(ext_pos+1);		
			
			//TODO instead of looking to extension, find out real file type through e.g. FileView.getTypeDescription(File f)
			//TODO put usable extensions in some sort of list
			//TODO at this moment there are files with same filename but different extension
			if(extension.equals("png") || extension.equals("PNG") || extension.equals("jpg") || 
					extension.equals("JPG") || extension.equals("jpeg") || extension.equals("JPEG") || 
					extension.equals("gif") || extension.equals("GIF")) {
				System.out.println(file.getAbsolutePath());
				try {
					BufferedImage im = ImageIO.read(file);
					images.put(filename, im);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	
	}
	
	public BufferedImage getImage(String key) {
		return images.get(key);
	}
        
        
 /**
 *Resizing an image and returning thumb picture ,used to set as an icon in toolbar of mapgenerator GUI
 *<br>
 * @param srcImg original image to resize
 * @param w width of the image
 * @param h height of the image
 * @return resizedImg resized copy of the original image
 * @see MapGenerator

 */               
  public static Image getScaledImage(Image srcImg, int w, int h){
        BufferedImage resizedImg = new BufferedImage(w,h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = resizedImg.createGraphics();

        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

        g2.drawImage(srcImg, 0, 0, w, h, null);
        g2.dispose();
        return resizedImg;
    }            
}
